import { getUrlValue } from "../_utils/url"

interface AuthCreateProps {
  // storage?: 'localStorage'
  loginUrl?: string
  authCode?:string
  prefix?: string
  navigateTo?:any
  extra?: string[]
}
function create({ extra,navigateTo,authCode='', loginUrl = '/login', prefix = '' }: AuthCreateProps) {
  const toLogin = () => { 
    if(navigateTo){
      navigateTo(loginUrl)
    }else{

      location.href = loginUrl
    }
  }
  const getAuthCode = ()=>{
     const query =  getUrlValue();
     return query[authCode]
  }
  const getToken = () => {
    return localStorage.getItem(`${prefix}token`) as string
  }
  const setItem = (key: string, value: any) => {
    localStorage.setItem(`${prefix}${key}`, value)
  }
  const getItem = (key: string) => {
    return localStorage.getItem(`${prefix}${key}`)
  }
  const setToken = (value: string) => {
    return localStorage.setItem(`${prefix}token`, value)
  }
  const exit = () => {
    localStorage.removeItem(`${prefix}extra`)
    localStorage.removeItem(`${prefix}token`)
  }
  const setExtra = (data: any) => {
    const map = {};
    if (extra) {
      extra.forEach(key => {
        map[key] = data[key]
      })
      setItem(`extra`, JSON.stringify(map))
    } else {
      setItem('extra', JSON.stringify(data))
    }
  }

  const getExtra = (key: string) => {
    const item  = JSON.parse(getItem('extra'))||{};
    return item[key]

  }
  return {
    toLogin,
    getAuthCode,
    exit,
    getToken,
    setToken,
    getExtra,
    setExtra
  }
}

export default {
  create
}


